/*
 *  Copyright 2010 mazhao.
 * 
 *  Licensed under the Apache License, Version 2.0 (the "License");
 *  you may not use this file except in compliance with the License.
 *  You may obtain a copy of the License at
 * 
 *       http://www.apache.org/licenses/LICENSE-2.0
 * 
 *  Unless required by applicable law or agreed to in writing, software
 *  distributed under the License is distributed on an "AS IS" BASIS,
 *  WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 *  See the License for the specific language governing permissions and
 *  limitations under the License.
 *  under the License.
 */

package shopping.customer;

import com.opensymphony.xwork2.ModelDriven;
import org.apache.struts2.convention.annotation.Action;
import org.apache.struts2.convention.annotation.Result;
import shopping.commons.BaseAction;
import shopping.commons.Util;
import shopping.model.*;

import java.util.*;
import java.util.Map.Entry;

/**
 *
 * @author mazhao
 */
public class CheckoutAction  extends BaseAction implements ModelDriven<Order>{

    /** order items */
    private Map<Product, Integer> items = new HashMap<Product, Integer>();

    public Map<Product, Integer> getItems() {
        return items;
    }

    /** province and city select list */
    private List<Province> provinces = new ArrayList<Province>();

    public List<Province> getProvinces() {
        return provinces;
    }

    @Action(value = "/customer/showcheckout",
    results = {
        @Result(name = "success", location = "/WEB-INF/content/customer/checkout.jsp")
    })
    public String showCheckout() {
        log.debug("enter show check out action");

        // 1. get shopping cart from session

        ShoppingCart sc = Util.Shopping.retriveShoppingCart();

        // 2. query price for each item
        Map<Integer, Integer> its = sc.getItems();
        Iterator<Map.Entry<Integer, Integer>> it = its.entrySet().iterator();
        while(it.hasNext()) {
            Entry<Integer, Integer> ent = it.next();

            // IMPLEMENTATION IN PRODUCT
            Product p = Product.getProductForCheckout(ent.getKey());
            this.items.put(p, ent.getValue());
        }

        log.debug("check out item size:" + items.size());

        // 3. initialize province and city list
        this.provinces = Province.getAll();

        return SUCCESS;
    }

    @Action(value = "/customer/checkout",
    results = {
        @Result(name = "success", location = "/WEB-INF/content/customer/checkout-success.jsp")
    })
    public String checkout() {
        log.debug("enter check out action");

        // 1. create order from input form
        LoginInfo loginInfo = Util.Security.retriveUserFromSession();

        model.setUsername(loginInfo.getUsername());
        model.setStatus(Order.ORDER_STATUS_NEW);

        model.beginTrans();

        model.insertOrder();

        log.debug("insert order successfully");

        // 2. create order items from shopping cart
        ShoppingCart sc = Util.Shopping.retriveShoppingCart();
        Map scitems = sc.getItems();
        Iterator<Entry<Integer, Integer>> it = scitems.entrySet().iterator();
        while(it.hasNext()) {
            Entry<Integer, Integer> ent = it.next();
            Map paraMap = new HashMap<String, Object>();
            paraMap.put("orderId", model.getId());
            paraMap.put("count", ent.getValue());
            paraMap.put("id", ent.getKey());

            log.debug("insert order item:" + paraMap);
            model.createOrderItem(paraMap);
        }

        model.commit();
        // 3. show order sending information(order id and postal infromation)

        // 4. remove shoppingcart item
        Util.Shopping.removeShoppingCart();

        return SUCCESS;
    }

    //==============================================
    // Model Drive Interface Property and Method.
    //==============================================
    private Order model = new Order();

    public Order getModel() {
        return model;
    }

}
